using System;
using System.Collections.Generic;
using System.Text;
using System.Threading;

namespace SanFS.MediaChangerService
{
    internal abstract class JobRequest : SanFS.MediaChangerService.IJobRequest
    {
        private ManualResetEvent    mRst;
        private JobStates           mState;
        private Exception           mErrException;
        private MediaChangerService mService;
        private TimeSpan            mEstimatedTTC;

        public event JobRequestCompleteHandler Completed;

        public JobRequest(MediaChangerService Service)
        {
            mService = Service;
            mRst = new ManualResetEvent(false);
            ResetPending();
        }

        protected abstract void RunJob();

        public void ExecuteJob()
        {
            try
            {
                mState = JobStates.Executing;
                RunJob();
                mState = JobStates.Completed;
            }
            catch (Exception ex)
            {
                mState = JobStates.Error;
                mErrException = ex;
                throw;
            }
        }

        public void ResetPending()
        {
            mState = JobStates.Pending;
            mErrException = null;
        }

        public void EmitJobCompleted()
        {
            if (Completed != null)
                Completed(this);
        }

        protected void SetEstimatedTTC(TimeSpan TTC)
        {
            mEstimatedTTC = TTC;
        }

        #region Properties

        public Exception ErrException
        {
            get { return mErrException; }
        }

        public JobStates State
        {
            get { return mState; }
        }

        public ManualResetEvent WaitEvent
        {
            get { return mRst; }
        }

        public MediaChangerService Service
        {
            get { return mService; }
        }

        public TimeSpan EstimatedTTC
        {
            get { return mEstimatedTTC; }
        }

        #endregion
    }  // END CLASS
}  // END NAMESPACE
